﻿<%@ WebHandler Language="C#" Class="ShowListTransfer" %>

using System;
using System.Web;
using System.Text;
using System.Data;
using Chenxin.Lib.Utility;
using Chenxin.Lib.Business;
using Chenxin.Lib.Business.BLL;

public class ShowListTransfer : AjaxHandlerBase
{
    /// <summary>
    /// 基本权限项
    /// </summary>
    public ShowListTransfer()
    {
        //导出
        htTypePermit.Add("export", Constants.Permit_Transfer_Export);  
    }
    
    override public void RequestProcess(HttpContext context)
    {
        context.Response.AddHeader("pragma", "no-cache");
        context.Response.AddHeader("cache-control", "");
        context.Response.CacheControl = "no-cache";
        string strOp = context.Request["op"];
        string strResponse = "";
        switch (strOp.ToLower())
        {
            //获取实体
            case "getmodel":
                strResponse = getModel(context);
                break;
            case "getmodel1":
                strResponse = getModel1(context);
                break;
            //查询
            case "search":
                strResponse = Search(context);
                break;
            default:
                break;
        }
        context.Response.Write(strResponse);
    }

    /// <summary>
    /// 获取实体
    /// </summary>
    /// <param name="context"></param>
    /// <returns></returns>
    public string getModel(HttpContext context)
    {
        try
        {
            string RecordId = context.Request["modelid"];
            Chenxin.Lib.Business.Entity.t_Contract_BaseInfo info = Chenxin.Lib.Business.DAL.t_Contract_BaseInfo.GetModel(new Guid(RecordId));
            if (info == null)
            {
                return string.Format("{{success:'1',msg:'{0}',data:''}}", Resources.Message.Msg_Search_NoData);
            }
            Chenxin.Lib.Business.Entity.t_Contract_Infomation info1 = Chenxin.Lib.Business.DAL.t_Contract_Infomation.GetModel(new Guid(RecordId));
            return string.Format("{{success:'1',msg:'成功',data:{{model:{0},model1:{1}}}}}", Chenxin.Lib.Utility.JsonHelp.Convert2Json(info), Chenxin.Lib.Utility.JsonHelp.Convert2Json(info1));
        }
        catch (Exception ex)
        {
            return string.Format("{{success:'0',msg:'{0}：{1}',data:''}}", Resources.Message.Global_Err_Exception, ex.Message);
        }
    }

    //*******************************************
    //功能概要       ：获得详细信息
    //参数説明       ：context 请求上下文
    //返回值説明     ：程序处理信息提示
    //功能詳細       ：获得详细信息
    //作成者         ：chen.yugong 
    //作成日         ：2010-06-29
    //修改者         ：
    //修改日         ：
    //*******************************************
    public string getModel1(HttpContext context)
    {
        try
        {
            string RecordId = context.Request["modelid"];
            Chenxin.Lib.Business.Entity.t_Contract_BaseInfo info = Chenxin.Lib.Business.DAL.t_Contract_BaseInfo.GetModel(new Guid(RecordId));
            if (info == null)
            {
                return string.Format("{{success:'1',msg:'{0}',data:''}}", Resources.Message.Msg_Search_NoData);
            }
            Chenxin.Lib.Business.Entity.t_Contract_Infomation info2 = Chenxin.Lib.Business.DAL.t_Contract_Infomation.GetModel(new Guid(RecordId));
            Chenxin.Lib.Business.Entity.t_Contract_Infomation1 info1 = Chenxin.Lib.Business.DAL.t_Contract_Infomation1.GetModel(new Guid(RecordId));
            return string.Format("{{success:'1',msg:'成功',data:{{model:{0},model1:{1},model2:{2}}}}}", Chenxin.Lib.Utility.JsonHelp.Convert2Json(info), Chenxin.Lib.Utility.JsonHelp.Convert2Json(info1), Chenxin.Lib.Utility.JsonHelp.Convert2Json(info2));
        }
        catch (Exception ex)
        {
            return string.Format("{{success:'0',msg:'{0}：{1}',data:''}}", Resources.Message.Global_Err_Exception, ex.Message);
        }
    }

    //*******************************************
    //功能概要       ：获得过户一览
    //参数説明       ：context 请求的上下文
    //返回值説明     ：无
    //功能詳細       ：获得过户一览
    //作成者         ：zou.xiaochun
    //作成日         ：2010-10-25
    //*******************************************
    private string Search(HttpContext context)
    {
        try
        {
            //页码
            int strPageIndex = (string.IsNullOrEmpty(context.Request["pageindex"])) ? 1 : int.Parse(context.Request["pageindex"]) + 1;
            //页显示行数
            int strPageSize = (string.IsNullOrEmpty(context.Request["pagesize"])) ? 30 : int.Parse(context.Request["pagesize"]);
            //查询条件
            string sqlWhere = GenerateCondition(context);
            
            //查询分页信息
            Chenxin.Lib.Business.BLL.ConfirmMainBusinessApply confirmMainBusinessApply = new Chenxin.Lib.Business.BLL.ConfirmMainBusinessApply();
            System.Data.DataSet ds = confirmMainBusinessApply.getTransferList(sqlWhere, strPageIndex, strPageSize);
            //总页数
            int count = (int)ds.Tables[1].Rows[0][0];

            return string.Format("{{success:'1',msg:'{0}',data:{{count:'{1}',{2}}}}}", Resources.Message.Global_Msg_SUCCESS, count, JsonHelp.Convert2Json(ds.Tables[0]));
        }
        catch (Exception ex)
        {
            return string.Format("{{success:'0',msg:'{0}：{1}',data:''}}", Resources.Message.Global_Err_Exception, ex.Message);
        }
    }

    //*******************************************
    //功能概要       ：查询权限
    //参数説明       ：context 请求上下文
    //返回值説明     ：程序处理信息提示
    //功能詳細       ：生成查询条件语句
    //作成者         ：chen.yugong
    //作成日         ：2010-06-29
    //修改者         ：王玮
    //修改日         ：2010-07-13
    //*******************************************
    public string GenerateCondition(HttpContext context)
    {
        try
        {
            //获取页面查询条件
            Guid city = (string.IsNullOrEmpty(context.Request["cityid"])) ? Guid.Empty : new Guid(context.Request["cityid"]);
            Guid company = (string.IsNullOrEmpty(context.Request["companyid"])) ? Guid.Empty : new Guid(context.Request["companyid"]);
            Guid businessdistrict = (string.IsNullOrEmpty(context.Request["areaid"])) ? Guid.Empty : new Guid(context.Request["areaid"]);
            Guid departs = (string.IsNullOrEmpty(context.Request["departid"])) ? Guid.Empty : new Guid(context.Request["departid"]);
            Guid employee = (string.IsNullOrEmpty(context.Request["userid"])) ? Guid.Empty : new Guid(context.Request["userid"]);
            string strDateType = context.Request.QueryString["DateType"];
            string strType = context.Request.QueryString["TransferType"];
            string starttime = context.Request.QueryString["DateFr"];
            string endtime = context.Request.QueryString["DateTo"];
            string keyword = context.Request.QueryString["KeyWord"];
            string strRegion = context.Request.QueryString["Region"];
            
            System.Text.StringBuilder sb = new System.Text.StringBuilder();

            sb.Append(" and a.BusinessType = 10 ");
            //判断级联菜单
            if (employee != Guid.Empty)
                sb.AppendFormat(" and (a.BuyerUserId = '{0}') ", employee);
            else if (departs != Guid.Empty)
                sb.AppendFormat(" and (a.BuyerDepartId = '{0}')", departs);
            else if (businessdistrict != Guid.Empty)
            {
                Chenxin.Lib.Hr.Entity.Hr_DepartmentInfo item = null;
                string strCachkey = string.Format(Chenxin.Lib.Cache.CacheDataType.GLOBAL_DEPARTMENT, businessdistrict);
                Chenxin.Lib.Cache.CacheService cs = new Chenxin.Lib.Cache.CacheService(Chenxin.Lib.Cache.CacheConn.xCacheConn.GLOBAL);
                item = cs.GetObject<Chenxin.Lib.Hr.Entity.Hr_DepartmentInfo>(strCachkey);
                if (!cs.Hit)
                {
                    item = Chenxin.Lib.Hr.DAL.Hr_DepartmentInfo.GetModel(businessdistrict);
                    if (item != null) cs.Set(strCachkey, item, DateTime.Now.AddDays(1));
                }

                if (item == null) return string.Format("{{success:'0',msg:'{0}',data:''}}", Resources.Message.Global_Err_GetBusDis);

                sb.AppendFormat(" and (a.BuyerDepartId in (select departId from v_Hr_DepartmentInfo where DepartSrc like '{0}%'))", item.DepartSrc);
            }
            else if (company != Guid.Empty)
            {
                sb.AppendFormat(" and a.BuyerCompanyId = '{0}'", company);
            }
            else if (city != Guid.Empty)
            {
                sb.AppendFormat(" and a.BuyerCityId = '{0}'", city);
            }
            else
            {
                sb.AppendFormat(" and a.BuyerCompanyId = '{0}'", CurrentUserInfo.CompanyId);
            }

            //查询权限判断权限
            System.Text.StringBuilder sb1 = new System.Text.StringBuilder();
            if (CurrentUserInfo.ContainsPermit(Constants.Permit_TransferSearch_All))
            {
                sb1.Append(" (1=1) ");
            }
            else if (CurrentUserInfo.ContainsPermit(Constants.Permit_TransferSearch_City))
            {
                sb1.AppendFormat(" (a.BuyerCityId = '{0}')", CurrentUserInfo.CityId);
            }
            else if (CurrentUserInfo.ContainsPermit(Constants.Permit_TransferSearch_Company))
            {
                sb1.AppendFormat(" (a.BuyerCompanyId = '{0}')", CurrentUserInfo.CompanyId);
            }
            else if (CurrentUserInfo.ContainsPermit(Constants.Permit_TransferSearch_Depart))
            {
                sb1.Append(" (EXISTS(");
                sb1.AppendFormat("Select 1 from t_Business_EmpSetting M WHERE a.BuyerDepartId=M.DepartId And M.Userid= '{0}' and SearchTransfer=1", CurrentUserInfo.UserId.ToString());
                sb1.Append(")) ");
            }
            else
            {
                sb1.AppendFormat(" (a.BuyerUserId = '{0}')", CurrentUserInfo.UserId);
            }

            if (!String.IsNullOrEmpty(sb.ToString()))
                sb1.Append(sb.ToString());

            //日期类型+日期
            if (!String.IsNullOrEmpty(strDateType))
            {
                switch (strDateType)
                {
                    case "发件日期":
                        //发件日期开始
                        if (!String.IsNullOrEmpty(starttime))
                        {
                            sb1.Append(string.Format(" and convert(varchar(10),(convert(datetime,c.SendDate,120)),120)  >= convert(varchar(10),(convert(datetime,'{0}',120)),120)", (starttime)));
                        }
                        //发件日期结束
                        if (!String.IsNullOrEmpty(endtime))
                        {
                            sb1.Append(string.Format(" and convert(varchar(10),(convert(datetime,c.SendDate,120)),120)  <= convert(varchar(10),(convert(datetime,'{0}',120)),120)", (endtime)));
                        }
                        break;
                    case "过户日期":
                        //过户日期开始
                        if (!String.IsNullOrEmpty(starttime))
                        {
                            sb1.Append(string.Format(" and convert(varchar(10),(convert(datetime,c.ReciveDate,120)),120)  >= convert(varchar(10),(convert(datetime,'{0}',120)),120)", (starttime)));
                        }
                        //过户日期结束
                        if (!String.IsNullOrEmpty(endtime))
                        {
                            sb1.Append(string.Format(" and convert(varchar(10),(convert(datetime,c.ReciveDate,120)),120)  <= convert(varchar(10),(convert(datetime,'{0}',120)),120)", (endtime)));
                        }
                        break;
                    case "签约日期":
                        //签约日期开始
                        if (!String.IsNullOrEmpty(starttime))
                        {
                            sb1.Append(string.Format(" and convert(varchar(10),(convert(datetime,a.ContractDate,120)),120)  >= convert(varchar(10),(convert(datetime,'{0}',120)),120)", (starttime)));
                        }
                        //签约日期结束
                        if (!String.IsNullOrEmpty(endtime))
                        {
                            sb1.Append(string.Format(" and convert(varchar(10),(convert(datetime,a.ContractDate,120)),120)  <= convert(varchar(10),(convert(datetime,'{0}',120)),120)", (endtime)));
                        }
                        break;
                    //case "收件收据日期":
                    //    //收件收据日期开始
                    //    if (!String.IsNullOrEmpty(starttime))
                    //    {
                    //        sb1.Append(string.Format(" and convert(varchar(10),(convert(datetime,c.ReciveDate,120)),120)  >= convert(varchar(10),(convert(datetime,'{0}',120)),120)", (starttime)));
                    //    }
                    //    //收件收据日期结束
                    //    if (!String.IsNullOrEmpty(endtime))
                    //    {
                    //        sb1.Append(string.Format(" and convert(varchar(10),(convert(datetime,c.ReciveDate,120)),120)  <= convert(varchar(10),(convert(datetime,'{0}',120)),120)", (endtime)));
                    //    }
                    //    break;
                }
            }

            if (!string.IsNullOrEmpty(strType))
            {
                switch (strType)
                {
                    case "已过户":
                        sb1.Append(" and c.ReciveCode is not null ");
                        break;
                    case "未过户":
                        sb1.Append(" and c.ReciveCode is null ");
                        break;
                }
            }

            if (!string.IsNullOrEmpty(strRegion))
            {
                    sb1.AppendFormat(" and a.Region ='{0}' ", strRegion);
            }
            
            if (!String.IsNullOrEmpty(keyword))
            {
                sb1.AppendFormat(" and ((a.HouseAddress LIKE '%{0}%') Or(a.ContractCode like '%{0}%'))", keyword);
            }
            return sb1.ToString();
        }
        catch (Exception ex)
        {
            return string.Format("{{success:'0',msg:'{0}：{1}',data:''}}", Resources.Message.Global_Err_Exception, ex.Message);
        }
    }
}